﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading;

public partial class UserControl_ControlMappingKhachHang : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (ViewState["flag"] == null)
            {
                
                AddNew();
            }
            //nằm trong thread
            ThreadStart thrstar = new ThreadStart(BindChannel);
            ThreadStart thrstart1 = new ThreadStart(BindTinhThanh);
            ThreadStart thrstart2 = new ThreadStart(LoadProvincePopup);
            ThreadStart thrstart3 = new ThreadStart(LoadGridDulicated);

            Thread tr = new Thread(thrstar);
            Thread tr1 = new Thread(thrstart1);
            Thread tr2 = new Thread(thrstart2);
            Thread tr3 = new Thread(thrstart3);

            tr.Start();
            tr1.Start();
            tr2.Start();
            tr3.Start();

            tr.Join();
            tr1.Join();
            tr2.Join();
            tr3.Join();
            // năm trong thread


            BindQuanHuyen(ddlProvince.SelectedValue.ToString());
            LoadTownPopup(DropGroup.SelectedValue.ToString());
            BindSubChannel(ddlChannel.SelectedValue.ToString());
           
        }
    }
    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }
    protected void imgBtnAdd_Click(object sender, ImageClickEventArgs e)
    {
        AddNew();
    }
    private void clearDetail()
    {
        txtMaSo.Text = "New";
        txtFimexKH.Text = "";
        txtAddress.Text = "";


    }
    void AddNew()
    {
        if (ViewState["KhoHangTemp"] != null)
        {
            ViewState["KhoHangTemp"] = null;

        }

        grvProduct.DataSource = null;
        grvProduct.DataBind();

        TabContainer1.ActiveTabIndex = 0;
        clearDetail();
        ViewState["flag"] = true;
       

        btnSave.Text = "Lưu";

    }
    void LoadProvincePopup()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            dt = new ClassExecute.ClassExecute();
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getTinhThanh", CommandType.StoredProcedure);
            dt.BindDropDownList(db, DropGroup, "MaTinh", "TinhThanh");
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    void LoadTownPopup(string MaTinh)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getQuanHuyen", CommandType.StoredProcedure,
            new SqlParameter("@MaTinh", MaTinh));
        dt.BindDropDownList(db,DropChannel, "MaQuan", "QuanHuyen");
    }
    protected void DropGroup_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindQuanHuyen(ddlProvince.SelectedValue.ToString());
    }
    protected void ddlProvince_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindQuanHuyen(ddlProvince.SelectedValue.ToString());
    }
    protected void ddlChannel_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindSubChannel(ddlChannel.SelectedValue.ToString());
    }
    void BindTinhThanh()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getTinhThanh", CommandType.StoredProcedure);
        dt.BindDropDownList(db, ddlProvince, "MaTinh", "TinhThanh");
    }
    void BindQuanHuyen(string MaTinh)
    { 
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getQuanHuyen", CommandType.StoredProcedure,
            new SqlParameter("@MaTinh", MaTinh));
        dt.BindDropDownList(db, ddlTown, "MaQuan", "QuanHuyen");
    }
    void BindChannel()
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getChannel", CommandType.StoredProcedure);
        dt.BindDropDownList(db, ddlChannel, "ChannelID", "ChannelName");
    }
    void BindSubChannel(string ChannelID)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getSubchannel", CommandType.StoredProcedure,
            new SqlParameter("@ChannelID", ChannelID));
        dt.BindDropDownList(db, ddlSubChannel, "SubChannelID", "ChannelName");
    }
    protected void LinkGetDKSH_Click(object sender, EventArgs e)
    {
        grvKH.DataSource = null;
        grvKH.DataBind();
        MessageBoxUserGroup.ShowOnPageLoad = true;
        lblSelectSPFor.Text = "Tìm kiếm những khách hàng của DKSH";
        ViewState["NPP"] = "FM_00000003";
    }
    protected void LinkGetNMD_Click(object sender, EventArgs e)
    {
        grvKH.DataSource = null;
        grvKH.DataBind();
        MessageBoxUserGroup.ShowOnPageLoad = true;
        lblSelectSPFor.Text = "Tìm kiếm những khách hàng của Nhật Minh Dương";
        ViewState["NPP"] = "FM_00000002";
    }
    protected void imgBtnDelete_Click(object sender, ImageClickEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            int i = dt.ExecuteSQl_int(str, "[k_DeleteMapCustomer]", CommandType.StoredProcedure, ref error,
                new SqlParameter("@FimexKey", txtMaSo.Text));
            if (i == 1)
            {
                ShowMessageBox("Đã xóa mã trùng khách hàng thành công");
                AddNew();
                LoadGridDulicated();
            }
            else
            {
                ShowMessageBox("Hệ thống đang bảo trì");
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }    
    }
    
    void UpdateGridProduct(string CustID,string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        DataTable table = new DataTable();
        DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getInfoCustForMap", CommandType.StoredProcedure,
                new SqlParameter("@CustID", CustID));
        if (ViewState["KhoHangTemp"] != null)
        {
            table = (DataTable)ViewState["KhoHangTemp"];
            foreach (DataRow dr in table.Rows)
            {
                if (dr[0].ToString() == CustID)
                {
                    return;
                }
            }
            
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[0] = CustID;
            row[1] = db.Rows[0]["customer_name"].ToString();
            row[2] = db.Rows[0]["Address"].ToString();
            row[3] = db.Rows[0]["ProvinceCode"].ToString();
            row[4] = sitecode;

            table.Rows.Add(row);
        }
        else
        {


            DataColumn col1 = new DataColumn("MaKH");
            DataColumn col2 = new DataColumn("TenKhachHang");
            DataColumn col3 = new DataColumn("DiaChi");
            DataColumn col4 = new DataColumn("ProvinceCode");
            DataColumn col5 = new DataColumn("NPP");
           

            col1.DataType = System.Type.GetType("System.String");
            col2.DataType = System.Type.GetType("System.String");
            col3.DataType = System.Type.GetType("System.String");
            col4.DataType = System.Type.GetType("System.String");
            col5.DataType = System.Type.GetType("System.String");

            table.Columns.Add(col1);
            table.Columns.Add(col2);
            table.Columns.Add(col3);
            table.Columns.Add(col4);
            table.Columns.Add(col5);

            

            //Create a Row in the DataTable table
            DataRow row = table.NewRow();
            //Fill All Columns with Data
            row[col1] = CustID;
            row[col2] = db.Rows[0]["customer_name"].ToString();
            row[col3] = db.Rows[0]["Address"].ToString();
            row[col4] = db.Rows[0]["ProvinceCode"].ToString();
            row[col5] = sitecode;

            table.Rows.Add(row);

            ViewState["KhoHangTemp"] = table;
        }
        grvProduct.DataSource = ViewState["KhoHangTemp"];
        grvProduct.DataBind();

      
    }
    protected void btGetSP_Click(object sender, EventArgs e)
    {
        LoadGridKH(DropGroup.SelectedValue.ToString(), DropChannel.SelectedValue.ToString(), ViewState["NPP"].ToString());
    }
    void LoadGridKH(string Province, string Town, string sitecode)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "[k_GetArcustForMap]", CommandType.StoredProcedure,
                new SqlParameter("@Province", Province),
                new SqlParameter("@Town", Town),
                new SqlParameter("@sitecode", sitecode));
            if (db.Rows.Count > 0)
            {
                grvKH.DataSource = db;
            }
            else
            {
                grvKH.DataSource = null;
            }
            grvKH.DataBind();
        }
        catch (Exception ex)
        {
            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if ((bool)ViewState["flag"])
            {
                //insert
                if (grvProduct.Rows.Count > 0)
                {
                    string Array = "";
                    DataTable dtLisProduct = new DataTable();
                    dtLisProduct = (DataTable)ViewState["KhoHangTemp"];

                    foreach (DataRow dr in dtLisProduct.Rows)
                    {

                        Array = Array + dr[0].ToString() + ",";

                    }
                    // ShowMessageBox(Array);
                    int i = dt.ExecuteSQl_int(str, "k_mapCustomer", CommandType.StoredProcedure, ref error,
                        new SqlParameter("@arrayCustID", Array.Substring(0, Array.Length - 1)),
                        new SqlParameter("@customer_name", txtFimexKH.Text),
                        new SqlParameter("@address",txtAddress.Text),
                        new SqlParameter("@ProvinceCode",ddlProvince.SelectedValue.ToString()),
                        new SqlParameter("@TownCode",ddlTown.SelectedValue.ToString()),
                        new SqlParameter("@Channel",ddlChannel.SelectedValue.ToString()),
                        new SqlParameter("@SubChannelDrID",ddlSubChannel.SelectedValue.ToString()));
                    if (i == 1)
                    {
                        ShowMessageBox("Bạn đã map khách hàng thành công");
                        AddNew();
                        LoadGridDulicated();
                    }
                    else
                    {
                        ShowMessageBox("Hệ thống đang bảo trì");
                    }
                }
                else
                {
                    ShowMessageBox("Đề nghị bạn chọn mã khách hàng muốn Map");
                }
            }
            else
            {
                //update
                if (grvProduct.Rows.Count > 0)
                {
                    string Array = "";
                    DataTable dtLisProduct = new DataTable();
                    dtLisProduct = (DataTable)ViewState["KhoHangTemp"];

                    foreach (DataRow dr in dtLisProduct.Rows)
                    {

                        Array = Array + dr[0].ToString() + ",";

                    }
                    // ShowMessageBox(Array);
                    int i = dt.ExecuteSQl_int(str, "[k_UpdateMapCustomer]", CommandType.StoredProcedure, ref error,
                        new SqlParameter("@arrayCustID", Array.Substring(0, Array.Length - 1)),
                        new SqlParameter("@customer_name", txtFimexKH.Text),
                        new SqlParameter("@address",txtAddress.Text),
                        new SqlParameter("@ProvinceCode",ddlProvince.SelectedValue.ToString()),
                        new SqlParameter("@TownCode",ddlTown.SelectedValue.ToString()),
                        new SqlParameter("@Channel",ddlChannel.SelectedValue.ToString()),
                        new SqlParameter("@SubChannelDrID",ddlSubChannel.SelectedValue.ToString()),
                        new SqlParameter("@FimexKey",txtMaSo.Text));
                    if (i == 1)
                    {
                        ShowMessageBox("Bạn đã cập nhật map khách hàng thành công");
                        LoadGridDulicated();
                    }
                    else
                    {
                        ShowMessageBox("Hệ thống đang bảo trì");
                    }
                }
                else
                {
                    ShowMessageBox("Đề nghị bạn chọn mã khách hàng muốn Map");
                }
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }    
    } 
    protected void grvProduct_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvProduct.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["KhoHangTemp"];

        int i = 0;
        foreach (DataRow dr in table.Rows)
        {
            if (dr[0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["KhoHangTemp"] = table;
                grvProduct.EditIndex = -1;
                grvProduct.DataSource = ViewState["KhoHangTemp"];
                grvProduct.DataBind();
                return;
            }
            i++;
        }
    }
    void LoadGridDulicated()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getDulicated", CommandType.StoredProcedure);
            if (db.Rows.Count > 0)
            {
                grvBranch.DataSource = db;
            }
            else
            {
                grvBranch.DataSource = null;
            }
            grvBranch.DataBind();
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }    
    }
    protected void grvBranch_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblMaSo = (Label)grv.FindControl("lblMaSo");
                Label lblTenKH = (Label)grv.FindControl("lblTenKH");

                DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getInfoCustMapped", CommandType.StoredProcedure,
                    new SqlParameter("@ParentKey", lblMaSo.Text));

                DataTable db1 = dt.Get_Data_DataTable(str, ref error, "k_getInforParentCust", CommandType.StoredProcedure,
                    new SqlParameter("@custid", lblMaSo.Text));

                if (ViewState["KhoHangTemp"] != null)
                {
                    ViewState["KhoHangTemp"] = null;
                }
                ViewState["KhoHangTemp"] = db;

                txtMaSo.Text = lblMaSo.Text;
                txtFimexKH.Text = lblTenKH.Text;
                txtAddress.Text = db1.Rows[0]["address"].ToString();
                try
                {
                    ddlProvince.SelectedValue = db1.Rows[0]["ProvinceCode"].ToString();
                    BindQuanHuyen(ddlProvince.SelectedValue.ToString());

                }
                catch
                {
                }
                try
                {
                    ddlTown.SelectedValue = db1.Rows[0]["TownCode"].ToString();
                }
                catch
                {
                }

                try
                {
                    ddlChannel.SelectedValue = db1.Rows[0]["ChannelID"].ToString();

                    BindSubChannel(ddlChannel.SelectedValue.ToString());

                }
                catch
                {
                }
                try
                {

                    ddlSubChannel.SelectedValue = db1.Rows[0]["SubChannelDrID"].ToString();
                }
                catch
                {
                }

                grvProduct.DataSource = db;
                grvProduct.DataBind();


                ViewState["flag"] = false;
                btnSave.Text = "Cập nhật";

                TabContainer1.ActiveTabIndex = 0;
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvBranch_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvBranch.PageIndex = e.NewPageIndex;
        LoadGridDulicated();
    }
    protected void grvKH_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (e.CommandName == "chon")
            {
                GridViewRow grv = ((Control)e.CommandSource).NamingContainer as GridViewRow;
                Label lblitemkey = (Label)grv.FindControl("lblitemkey");
                if (ViewState["NPP"].ToString() == "FM_00000003")
                {
                    UpdateGridProduct(lblitemkey.Text, "DKSH");
                }
                else if (ViewState["NPP"].ToString() == "FM_00000002")
                {
                    UpdateGridProduct(lblitemkey.Text, "NMD");
                }
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
    protected void grvKH_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grvKH.PageIndex = e.NewPageIndex;
        LoadGridKH(DropGroup.SelectedValue.ToString(), DropChannel.SelectedValue.ToString(), ViewState["NPP"].ToString());
    }
}